package com.yupi.project.service.rpcimpl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guazai.common.pojo.UserInterfaceInfo;
import com.guazai.common.rpc.UserInterfaceInfoRPC;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.project.service.UserInterfaceInfoService;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;

/**
 * @author qiteng
 */
@DubboService
public class userInterfaceInfoRPCImpl implements UserInterfaceInfoRPC {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        //判断参数是否正确
        if (userId < 0 || interfaceInfoId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //如果数据库中有这条数据，就修改---totalNum = totalNum + 1  leftNum = leftNum - 1
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userId", userId);
        updateWrapper.eq("interfaceInfoId", interfaceInfoId);
        updateWrapper.setSql("totalNum = totalNum + 1, leftNum = leftNum - 1");
        if(!userInterfaceInfoService.update(updateWrapper)) {
            //如果没有，加插入数据---userId  interfaceInfoId  totalNum = 1  leftNum = 99，直接返回调用结果
            UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setUserId(userId);
            userInterfaceInfo.setInterfaceInfoId(interfaceInfoId);
            userInterfaceInfo.setTotalNum(1);
            userInterfaceInfo.setLeftNum(99);
            return userInterfaceInfoMapper.insert(userInterfaceInfo) > 0;
        } else {
            return true;
        }
    }
}
